/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.mqtt.server.util;

import com.alibaba.fastjson2.JSON;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;

/**
 * <b>(ProtoBufUtil)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/7/23
 */
public class ProtoBufUtil {

    public static <T> T deserialization(@NotEmpty String json, @NotNull Message.Builder builder) throws InvalidProtocolBufferException {
        JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
        return (T) builder.build();
    }

    public static <T> T deserialization(@NotNull Object obj, @NotNull Message.Builder builder) throws InvalidProtocolBufferException {
        JsonFormat.parser().ignoringUnknownFields().merge(JSON.toJSONString(obj), builder);
        return (T) builder.build();
    }

    public static byte[] deserializationToByteArray(@NotNull Object obj, @NotNull Message.Builder builder) throws InvalidProtocolBufferException {
        JsonFormat.parser().ignoringUnknownFields().merge(JSON.toJSONString(obj), builder);
        return builder.build().toByteArray();
    }

    public static byte[] deserializationToByteArray(@NotEmpty String json, @NotNull Message.Builder builder) throws InvalidProtocolBufferException {
        JsonFormat.parser().ignoringUnknownFields().merge(json, builder);
        return builder.build().toByteArray();
    }

    public static String deserializationToJson(@NotNull Message message) throws InvalidProtocolBufferException {
        return JsonFormat.printer().print(message);
    }

    public static <T> T deserialization(@NotNull Message message, Class<T> cls) throws InvalidProtocolBufferException {
        return JSON.parseObject(deserializationToJson(message), cls);
    }
}